package com.xncoding.pos.async;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 定时任务专用线程池
 *
 * @Description ScheduledConfig
 * @Author guoyb
 * @Date 2025/11/4 14:12
 */
@Configuration
@EnableAsync
public class ScheduledConfig implements AsyncConfigurer {


    public Executor executor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心池的大小（即线程池中的线程数目大于这个参数时，提交的任务会被放进任务缓存队列）
        executor.setCorePoolSize(10);
        // 线程池最大能容忍的线程数
        executor.setMaxPoolSize(20);
        // 任务缓存队列，用来存放等待执行的任务
        executor.setQueueCapacity(30);
        // 设置默认线程名称
        executor.setThreadNamePrefix("Scheduled_");
        // 设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardOldestPolicy());
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.initialize();
        return executor;
    }

    /**
     * 指定默认线程池
     */
    @Override
    public Executor getAsyncExecutor() {
        return this.executor();
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new AsyncExceptionHandler();
    }
}
